<?php

/**
 * Created by PhpStorm.
 * User: zcw 812039610@qq.com
 * Date: 2019/7/9
 * Time: 11:30
 */

namespace scripts;

use globalunit\logic\Web3DLogic;
use globalunit\model\AdvBaseConfigModel;
use globalunit\model\AdvChildModel;
use globalunit\model\AdvModel;
use globalunit\model\GameConfigModel;
use globalunit\model\HallConfigModel;
use globalunit\model\LuckyDrawLogModel;
use globalunit\model\MsgLogModel;
use globalunit\utils\GenID;
use globalunit\utils\QueueHelper;
use globalunit\utils\Tools;
use QYS\Protocol\Response;
use QYS\Protocol\Request;
use QYS\Db\Mysql;
use QYS\Db\Mongo;
use QYS\Db\Redis;
use QYS\Log\Log;
use globalunit\utils\Config;
use QYS\Core\Config  as CoreConfig;
use globalunit\model\UserModel;
use globalunit\model\MsgModel;
use globalunit\model\NoticeConfigModel;
use globalunit\model\ShareConfigModel;
use globalunit\model\SpaceBaseConfigModel;
use globalunit\model\SpaceConfigModel;
use globalunit\model\SponsorConfigModel;
use globalunit\model\StarLogModel;
use globalunit\model\TaskLogModel;
use globalunit\model\WayConfigModel;
use globalunit\model\Web3DModel;
use globalunit\utils\JWTUtil;
use globalunit\utils\KeysUtil;

function decryptLong($encryptData){
    $key_content = "-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAO/c4xhnz+HCQlq0
C0iLumxoTnUqTerWYz0lj4//6m/x5YgoOaZP07uhe+pNHpN5adVlHGbjEt2y3wu0
iH9TdCOoBO8Id1HK9HwSJsMmTJObqGTArXpVDOgioSqBUoEtFaqKBfG8n9iOEADc
a/X0frc26PfzKaDhFGkdEyTzFpPpAgMBAAECgYAJ0sYKLdY5rLcC9/SuV+qenfb4
nW7rezQ9QNiMUTLMut9noB4cTZCiUo68ncPuzj4jWyy6mfof0j+IPzCH5mcPKnlO
XAQ84qKqHdAqmY4MYKvCrLgOrUuDVqXOXUuzGNHYNPbB7wcr3bXvre3fbk5wmBXX
fPaRJVpFm36JmJmOsQJBAPzTCR21Rli+EIac9Ukgn4EpSWgDedE1IW1faDRwUPpL
Hz/3GN7T3nVQY2vTs8rZLQOBNs06QeaFKLvu1eAVOB8CQQDy4CxfQWLr9d8ZoKft
5ZHLII1gCK028s3ANjeDPnqLmHeQW0GdNuh2bjf34ugbWhqOWzR7MxSXCdGR9mwm
7NL3AkEA0MDruQTxpdqhyJSXD5+JNFvDycd88RoelLF/WDUZF+GpVuaPOYXVHCaZ
QPIXdTlnKoqplkExIsb2QF7PZ+v9XwJAQLd5O1yZ9lQKwbJsbNiqM50V7swBE845
AwmvWxpv3viei2m1nyW9ZalS4ouk23zz7JDi+B0RVHm6TRGDmg+q2wJBAI3F9hCl
GpymaFYUTVsUXAA8G/C2RKa1PGSDriu0e0iEzCKLlm9k8l8vYhsEUmHKZ2CaQsB/
HfmBAeARVvE8GVU=
-----END PRIVATE KEY-----";
    $rsaPrivateKey    = openssl_get_privatekey($key_content);

    $crypto = '';

    foreach (str_split(base64_decode($encryptData), 128) as $chunk) {

        openssl_private_decrypt($chunk, $decryptData, $rsaPrivateKey);

        $crypto .= $decryptData;
    }

    return $crypto;
}

class CMDINDEX
{

    public static function initconfig($request, $response, $rediscli)
    {

        $halls = [2, 4, 5];
        foreach ($halls as $k => $v) {
            for ($i = 1; $i < 21; $i++) {
                $m = new AdvBaseConfigModel();
                $m->space_id = $v;
                $m->pos = $i;
                $m->name = "展位:" . $i;
                $ok = $m->insert();
                if (!$ok) {
                    return ["errcode" => 10001, "data" => []];
                }
            }
        }
        return ["errcode" => 0, "data" => []];
    }

    public static function test($request, $response, $rediscli){
        Log::var_dump(["request" => $request]);
        $raw = $request->getRequest()->rawContent();
        Log::var_dump(["raw" => $raw]);
        $encryptData = "A1/tF9qLA48Hk4tWC/p8Sm1j5O9FWSy55TOcmo7v2JsvU4A2QyPXWcJTBHg1Wji+7kDpE68AJXRQg8WJeP9Pe5yXEjHKToMW2QGO+XQVLMg3GXMAwu3m6/rLx/F1wE8Snw0Uu6iISwTLD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XKD1qQJFoPKlNxhk9Wni58rvewmYUfIdrnnKoyEU60ld7ZuznLUyvJjsr3BCLhCcltT/wqFmzxxnqmsHPHJY/4gCaANF4Knmr1VhRdb7doN4Xs9UWaueRHm8P/xo3ig3LNUvi9pGILhQ==";
        $a = decryptLong($encryptData);
        return ["errcode" => 0, "data" => ["a" => $a]];
    }

    public static function checkjwt($request, $response, $rediscli)
    {
        $jwt = $request->getString("jwt");
        if (empty($jwt)) {
            return ["errcode" => 1, "errmsg" => "参数错误"];
        }
        $GAMENAME =  $GLOBALS['GAMENAME'];
        $VERSION =  $GLOBALS['VERSION'];
        try {
            $jwtobj = JWTUtil::decode($jwt, "$GAMENAME-$VERSION", array('HS256'));
        } catch (\Exception $e) {
            return ["errcode" => 2, "errmsg" => $e->getMessage()];
        }
        if (empty($jwtobj) || empty($jwtobj->id) || empty($jwtobj->appid) || empty($jwtobj->token)) {
            return ["errcode" => 3, "errmsg" => "jwt 解析失败"];
        }
        $id = $jwtobj->id;
        $token = $jwtobj->token;
        $tokenkey = KeysUtil::get_main_token($id);
        $token0 = $rediscli->get($tokenkey);
        if ($token0 != $token) {
            return ["errcode" => 4, "errmsg" => "token错误"];
        }

        $res = Web3DLogic::getWeb3dByAppid($jwtobj->appid);

        if (empty($res)) {
            return ["errcode" => 5, "errmsg" => "活动验证失败!"];
        }

        //活动未开始
        if (strtotime($res["start_time"]) > time()) {
            return ["errcode" => 5, "errmsg" => "活动未开始!"];
        }

        //活动已结束
        if (strtotime($res["end_time"]) < time()) {
            return ["errcode" => 6, "errmsg" => "活动已结束!"];
        }

        return ["errcode" => 0, "data" => []];
    }

    public static function createrole($request, $response, $rediscli)
    {
        $id = $request->getString("id");
        $nickname = $request->postString("nickname");
        $sex = $request->postInt("sex");
        if (empty($id) || empty($nickname) || empty($sex)) {
            return ["errcode" => 10001];
        }
        $model = new UserModel();
        $ok = $model->get("id = {$id}");
        if (!$ok) {
            return ["errcode" => 10007];
        }
        $model->nickname = $nickname;
        $model->sex = $sex;
        $ok = $model->save();
        if (!$ok) {
            return ["errcode" => 10008];
        }
        return ["errcode" => 0, "data" => ["user" => $model->toArray()]];
    }


    public static function loadappconfig($request, $response, $rediscli)
    {
        $wid = $request->getInt("wid");
        if (empty($wid)) {
            return ['errcode' => 10001];
        }
        $model = new Web3DModel();
        $ok = $model->get("id = {$wid}");
        if (!$ok) {
            return ['errcode' => 10006];
        }
        $app = $model->toArray();

        $model = new SponsorConfigModel();
        $res = $model->where("wid = {$wid}")->select();
        $sponsor = [];
        if ($res) {
            $sponsor = $res[0];
        }

        $model = new ShareConfigModel();
        $shares = $model->where("wid = {$wid}")->select();

        $model = new SpaceConfigModel();
        $spaces = $model->where("wid = {$wid}")->order("sort asc")->select();

        $m = new WayConfigModel();
        $ways = $m->where("wid = {$wid}")->order("sort asc")->select();

        $m = new HallConfigModel();
        $res = $m->where("wid = {$wid}")->select();
        $hall = [];
        if ($res) {
            $hall = $res[0];
        }

        $m = new SpaceBaseConfigModel();
        $space_advs = $m->where("id != 1 and id != 3")->order("id asc")->select();
        foreach ($space_advs as $k => $v) {
            $model = new AdvModel();
            $advs = $model->where("wid = {$wid} and space_id = {$v['id']}")->order("pos asc")->select();
            foreach ($advs as $k1 => $v1) {
                $model = new AdvChildModel();
                $childs = $model->where("aid = {$v1['id']}")->select();
                $advs[$k1]['childs'] = $childs;
            }
            $space_advs[$k]["advs"] = $advs;
        }

        $m = new GameConfigModel();
        $games = $m->where("wid = {$wid}")->order("pos asc")->select();

        $m = new MsgModel();
        $msgs = $m->where("wid = {$wid}")->select();

        return ["errcode" => 0, "data" => ["app" => $app, "sponsor" => $sponsor, "shares" => $shares, "spaces" => $spaces, "hall" => $hall, "space_advs" => $space_advs, "ways" => $ways, "games" => $games, "msgs" => $msgs]];
    }

    public static function loadnotices($request, $response, $rediscli)
    {
        $wid = $request->getInt("wid");
        if (empty($wid)) {
            return ['errcode' => 10001];
        }
        $m = new NoticeConfigModel();
        $notices = $m->where("wid = {$wid} and status = 1")->order("created_at desc")->select();
        return ["errcode" => 0, "data" => ["notices" => $notices]];
    }

    //完成任务
    public static function completetask($request, $response, $rediscli)
    {
        $id = $request->getInt("id");
        $wid = $request->getInt("wid");
        $space_id = $request->getInt("space_id");
        if (empty($id) || empty($space_id)) {
            return ["errcode" => 10001];
        }
        $u = new UserModel();
        $ok = $u->get($id);
        if (!$ok) {
            return ["errcode" => 10007];
        }

        $last_get_star_time = $u->last_get_star_time;
        $t = date("Ymd", strtotime($last_get_star_time));
        if($t != date("Ymd")){
            $u->cleanstar();
            if (!$ok) {
                return ["errcode" => 10011, "errmsg" => "系统繁忙, 请稍有再试!"];
            }
        }

        $m = new TaskLogModel();
        $ok = $m->where("wid = {$wid} and uid = {$id} and space_id = {$space_id} and to_days(created_at) = to_days(now())")->get();
        if ($ok) {
            return ["errcode" => 10010];
        }

        $mysql = Mysql::getInstance("mysql1");
        $mysql->query("start transaction");

        try {
            $m = new TaskLogModel();
            $m->wid = $wid;
            $m->uid = $id;
            $m->space_id = $space_id;
            $m->num = 1;
            $ok = $m->insert();
            if (!$ok) {
                throw new \Exception("TaskLogModel insert fail sql =" . $u->getLastSql());
            }
            $u = new UserModel();
            $u->get($id);
            $ok = $u->addstar();
            if (!$ok) {
                throw new \Exception("user addstar fail sql =" . $u->getLastSql());
            }

            $m = new StarLogModel();
            $m->wid = $wid;
            $m->uid = $id;
            $m->desc = "完成任务";
            $m->space_id = $space_id;
            $m->num = 1;
            $ok = $m->insert();
            if (!$ok) {
                throw new \Exception("StarLogModel insert fail sql =" . $u->getLastSql());
            }

            $mysql->commit();
        } catch (\Exception $e) {
            $mysql->rollback();
            Log::var_dump(["Exception" => $e->getMessage()]);
            return ['errcode' => 10009];
        }

        $u = new UserModel();
        $u->get($id);

        return ["errcode" => 0, "data" => ["user" => $u->toArray()]];
    }


    public static function todayluckydraw($request, $response, $rediscli)
    {
        $id = $request->getInt("id");
        $wid = $request->getInt("wid");
        if (empty($id)) {
            return ["errcode" => 10001];
        }

        $u = new UserModel();
        $ok = $u->get($id);
        if (!$ok) {
            return ["errcode" => 10007];
        }

        $m = new LuckyDrawLogModel();
        $ok = $m->where("wid = {$wid} and uid = {$id} and to_days(created_at) = to_days(now())")->get();
        if ($ok) {
            return ["errcode" => 10011];
        }

        return ["errcode" => 0, "data" => ["user" => $u->toArray()]];
    }


    public static function luckydraw($request, $response, $rediscli)
    {
        $id = $request->getInt("id");
        $wid = $request->getInt("wid");
        if (empty($id)) {
            return ["errcode" => 10001];
        }

        $u = new UserModel();
        $ok = $u->get($id);
        if (!$ok) {
            return ["errcode" => 10007];
        }

        $m = new LuckyDrawLogModel();
        $ok = $m->where("wid = {$wid} and uid = {$id} and to_days(created_at) = to_days(now())")->get();
        if ($ok) {
            return ["errcode" => 10011];
        }

        $cur_star_num = $u->star_num;
        if ($cur_star_num < 3) {
            return ["errcode" => 10012];
        }
        $mysql = Mysql::getInstance("mysql1");
        $mysql->query("start transaction");
        try {
            $u = new UserModel();
            $u->get($id);
            $ok = $u->descstar(3);
            if (!$ok) {
                throw new \Exception("user descstar fail sql =" . $u->getLastSql());
            }
            $m = new LuckyDrawLogModel();
            $m->uid = $id;
            $m->cur_star_num = $cur_star_num;
            $m->star_num = 3;
            $m->last_star_num = $u->star_num;
            $ok = $m->insert();
            if (!$ok) {
                throw new \Exception("LuckyDrawLogModel insert fail sql =" . $u->getLastSql());
            }

            $m = new StarLogModel();
            $m->wid = $wid;
            $m->uid = $id;
            $m->desc = "抽奖成功";
            $m->num = -3;
            $ok = $m->insert();
            if (!$ok) {
                throw new \Exception("TaskLogModel insert fail sql =" . $u->getLastSql());
            }

            $mysql->commit();
        } catch (\Exception $e) {
            $mysql->rollback();
            Log::var_dump(["Exception" => $e->getMessage()]);
            return ['errcode' => 10009];
        }

        $u = new UserModel();
        $u->get($id);

        return ["errcode" => 0, "data" => ["user" => $u->toArray()]];
    }

    public static function sendmsg($request, $response, $rediscli)
    {
        $id = $request->getInt("id");
        $wid = $request->getInt("wid");
        $msg = $request->postString("msg");
        if (empty($msg)) {
            return ["errcode" => 10001];
        }

        $u = new UserModel();
        $ok = $u->get($id);
        if (!$ok) {
            return ["errcode" => 10007];
        }

        $m = new MsgLogModel();
        $m->wid = $wid;
        $m->uid = $id;
        $m->msg = $msg;
        $ok = $m->insert();
        if (!$ok) {
            return ["errcode" => 10009];
        }
        return ["errcode" => 0];
    }
}

class IndexCtrl
{

    public function invoke($request, $response, $params)
    {
        $response->addHeader("Content-Type", 'application/json');
        $response->addHeader("Access-Control-Allow-Origin", "*");
        $response->addHeader("Access-Control-Allow-Methods", 'POST, GET, OPTIONS, DELETE');
        $response->addHeader('Access-Control-Allow-Headers', "Origin, X-Requested-With, Content-Type, Accept");
        $response->sendHttpHeader();
        $fname = $params['fname'];
        $rediscli = Redis::getInstance("redis1");
        $result = null;
        $result = CMDINDEX::$fname($request, $response, $rediscli);
        if (isset($result['errcode']) && $result['errcode'] != 0) {
            $errcode = $result['errcode'];
            if (!isset($result['errmsg'])) {
                $result['errmsg'] = Config::get('errmsg', 'e' . $errcode);
            }
        }
        Log::info('debug', $request, ['fname' => $fname, 'result' => $result]);
        $response->say(json_encode($result));
    }
}
